package com.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.Result;
import com.example.dto.ExpensesDto;
import com.example.entity.Expenses;
import com.example.entity.ExpensesUser;
import com.example.entity.User;
import com.example.entity.Wages;
import com.example.service.ExpensesService;
import com.example.service.ExpensesUserService;
import com.example.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Api(tags = {"报销接口列表"})
@RestController
@RequestMapping("/expenses")
@Slf4j
public class ExpensesController {

    @Autowired
    private ExpensesService expensesService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ExpensesUserService expensesUserService;

    @Autowired
    private UserService userService;


    @ApiOperation("添加报销信息")
    @PostMapping
    public Result<?> addExpenses(HttpServletRequest request, @RequestBody Expenses expenses) {

        log.info("{}", expenses);
        String header = request.getHeader("X-Token");
        Object o = redisTemplate.opsForValue().get(header);
        User user = (User) o;



        Long id = IdWorker.getId();
        expenses.setId(id);
        expenses.setStatusFinance(1);
        expenses.setStatusAdmin(1);


        log.info("{}", expenses);

        expensesService.save(expenses);

        ExpensesUser expensesUser = new ExpensesUser();
        expensesUser.setExpensesId(id);
        expensesUser.setUserId(user.getId());
        Long id1 = IdWorker.getId();
        expensesUser.setId(id1);
        expensesUserService.save(expensesUser);
        return Result.success("申请报销已提交");
    }

    @ApiOperation("查询报销信息")
    @GetMapping("/list")
    public Result<?> list(int page, int pageSize, String name) {
        Page<ExpensesUser> expensesUserPage = new Page<>(page, pageSize);
        Page<ExpensesDto> expensesDtoPage = new Page<>(page, pageSize);

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(name), User::getUsername, name);
        List<User> userList = userService.list(wrapper);

        List<Long> ids = userList.stream().map(item -> {
            Long id = item.getId();
            return id;
        }).collect(Collectors.toList());

        LambdaQueryWrapper<ExpensesUser> expensesUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        expensesUserLambdaQueryWrapper.in(ExpensesUser::getUserId,ids);
        expensesUserService.page(expensesUserPage,expensesUserLambdaQueryWrapper);

        List<ExpensesUser> expensesUserPageRecords = expensesUserPage.getRecords();

        List<ExpensesDto> collect = expensesUserPageRecords.stream().map(item -> {
            ExpensesDto expensesDto = new ExpensesDto();
            BeanUtils.copyProperties(item, expensesDto);

            LambdaQueryWrapper<Expenses> expensesLambdaQueryWrapper = new LambdaQueryWrapper<>();
            expensesLambdaQueryWrapper.eq(Expenses::getId, item.getExpensesId());
            Expenses one = expensesService.getOne(expensesLambdaQueryWrapper);
            BeanUtils.copyProperties(one, expensesDto);

            String date111 = String.valueOf(one.getDate());
            String str = date111.substring(0,10);

            expensesDto.setDate1(str);
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getId, item.getUserId());
            User one1 = userService.getOne(userLambdaQueryWrapper);
            expensesDto.setUserName(one1.getUsername());

            log.info("{}",one);
            log.info("{}",expensesDto);

            return expensesDto;
        }).collect(Collectors.toList());

        expensesDtoPage.setRecords(collect);
        Map<String, Object> map = new HashMap<>();
        map.put("total", expensesUserPage.getTotal());
        map.put("rows", expensesDtoPage.getRecords());
        return Result.success(map);
    }

    @ApiOperation("查询登录用户对应的报销信息")
    @GetMapping("/userList")
    public Result<?> list(HttpServletRequest request,int page, int pageSize) {
        String header = request.getHeader("X-Token");
        Object o = redisTemplate.opsForValue().get(header);
        User user = (User) o;

        log.info("{}",user);

        Page<ExpensesUser> expensesUserPage = new Page<>(page, pageSize);
        Page<ExpensesDto> expensesDtoPage = new Page<>(page, pageSize);

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getId,user.getId());
        List<User> userList = userService.list(wrapper);

        List<Long> ids = userList.stream().map(item -> {
            Long id = item.getId();
            return id;
        }).collect(Collectors.toList());

        LambdaQueryWrapper<ExpensesUser> expensesUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        expensesUserLambdaQueryWrapper.in(ExpensesUser::getUserId,ids);
        expensesUserService.page(expensesUserPage,expensesUserLambdaQueryWrapper);

        List<ExpensesUser> expensesUserPageRecords = expensesUserPage.getRecords();

        List<ExpensesDto> collect = expensesUserPageRecords.stream().map(item -> {
            ExpensesDto expensesDto = new ExpensesDto();
            BeanUtils.copyProperties(item, expensesDto);

            LambdaQueryWrapper<Expenses> expensesLambdaQueryWrapper = new LambdaQueryWrapper<>();
            expensesLambdaQueryWrapper.eq(Expenses::getId, item.getExpensesId());
            Expenses one = expensesService.getOne(expensesLambdaQueryWrapper);
            BeanUtils.copyProperties(one, expensesDto);

            String date111 = String.valueOf(one.getDate());
            String str = date111.substring(0,10);

            expensesDto.setDate1(str);
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getId, item.getUserId());
            User one1 = userService.getOne(userLambdaQueryWrapper);
            expensesDto.setUserName(one1.getUsername());

            log.info("{}",one);
            log.info("{}",expensesDto);

            return expensesDto;
        }).collect(Collectors.toList());

        expensesDtoPage.setRecords(collect);
        Map<String, Object> map = new HashMap<>();
        map.put("total", expensesUserPage.getTotal());
        map.put("rows", expensesDtoPage.getRecords());
        return Result.success(map);
    }


    @ApiOperation("报销申请的通过判断")
    @PutMapping("/status")
    public Result<?> updateExpenses(@RequestBody Expenses expenses) {
        log.info("{}", expenses);
        LambdaQueryWrapper<Expenses> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Expenses::getId, expenses.getId());
        Expenses one = expensesService.getOne(wrapper);
        one.setStatusFinance(expenses.getStatusFinance());
        one.setStatusAdmin(expenses.getStatusAdmin());
        expensesService.updateById(one);
        return Result.success("修改报销信息成功");
    }

}
